import './assets/main.css'

import { createApp, ref } from 'vue'
import type { App as VueApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from '@/router'
import '../mock'

import { CREATE_WINDOW, MAIN_WORLD_PORT, CHILD_TO_CHILD_WORLD_PORT } from './consts/ipc.js'

import { isObject } from '@/utils'

import {
  VxeUI,
  VxeButton,
  VxeButtonGroup,
  VxeDrawer,
  VxeForm,
  VxeFormGroup,
  VxeFormItem,
  VxeIcon,
  VxeLoading,
  VxeModal,
  VxePrint,
  VxeTooltip,
  VxeUpload,
  VxeTabPane,
  VxeTabs,
  VxeTag,
  VxePager,
} from 'vxe-pc-ui'

import { VxeTable, VxeColumn, VxeColgroup, VxeGrid, VxeToolbar } from 'vxe-table'

// 导入主题变量，也可以重写主题变量
import 'vxe-table/styles/cssvar.scss'
import 'vxe-pc-ui/styles/cssvar.scss'

// 导入默认的语言
import zhCN from 'vxe-pc-ui/lib/language/zh-CN'

VxeUI.setI18n('zh-CN', zhCN)
VxeUI.setLanguage('zh-CN')

// 可选组件
function lazyVxeUI(app: VueApp) {
  app.use(VxeButton)
  app.use(VxeButtonGroup)
  app.use(VxeDrawer)
  app.use(VxeForm)
  app.use(VxeFormGroup)
  app.use(VxeFormItem)
  app.use(VxeIcon)
  app.use(VxeLoading)
  app.use(VxeModal)
  app.use(VxePager)
  app.use(VxePrint)
  app.use(VxeTooltip)
  app.use(VxeUpload)
  app.use(VxeTabPane)
  app.use(VxeTabs)
  app.use(VxeTag)
}

function lazyVxeTable(app: VueApp) {
  app.use(VxeTable)
  app.use(VxeColumn)
  app.use(VxeColgroup)
  app.use(VxeGrid)
  app.use(VxeToolbar)
}

const app: VueApp = createApp(App)

app.use(createPinia())
app.use(router)

app.use(lazyVxeUI).use(lazyVxeTable).mount('#app')

const $ipcApi = ref()
const $electronApi = ref()

app.config.globalProperties.$ipcApi = $ipcApi
app.config.globalProperties.$electronApi = $electronApi

const ipcListener: { [key: string]: Array<(args: unknown) => void> } = {}
$ipcApi.value = {}
$ipcApi.value.addIpcListener = (type: string, listener: (args: unknown) => void) => {
  if (!ipcListener[type]) {
    ipcListener[type] = []
  }
  ipcListener[type].push(listener)
}

window.onmessage = (event) => {
  console.log('event---', event)
  if (event.source === window) {
    // 子进程与主进程通信
    if (event.data === MAIN_WORLD_PORT) {
      const [port] = event.ports
      port.onmessage = (event) => {
        console.log('来自主进程的消息:', event.data)
        setTimeout(() => {
          // 暴露主进程的API
          $electronApi.value = {
            createWindow: (url: string) => {
              port.postMessage({
                type: CREATE_WINDOW,
                url,
              })
            },
          }
        })
      }
    }

    // 子进程与子进程通信
    if (isObject(event.data) && event.data.type === CHILD_TO_CHILD_WORLD_PORT) {
      // isFirst代表第一个子进程，port1第一个子进程用，port2其它子进程用
      const [port] = event.ports
      const { isFirst } = event.data.data
      // const listeners: { [key: string]: Array<(args: unknown) => void> } = {}

      port.onmessage = (ev) => {
        if (isFirst) {
          console.log('来自其它子进程的消息:', ev)
        } else {
          console.log('来自第一个子进程的消息:', ev)
        }

        const { type, value } = ev.data
        const listeners = ipcListener
        console.log('listeners[type]', listeners, listeners[type])
        if (listeners[type] && listeners[type].length) {
          listeners[type].forEach((listener) => {
            listener(value)
          })
        }
      }
      setTimeout(() => {
        // 暴露当前进程窗口应用的API
        const api = {
          fireMessage: (type: string, value: unknown) => {
            port.postMessage({
              type,
              value,
            })
          },
        }
        if (isFirst) {
          $ipcApi.value.otherRenderApi = api
        } else {
          $ipcApi.value.mainRenderApi = api
        }
      })
    }
  }
}
